package utils;

import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

public class Ciphering {
	
	Cipher aes;
	static SecretKeySpec key = null;
	
	public static SecretKeySpec Key(){
		
        MessageDigest digest;
        if(key == null) {
        	try {
        		String passphrase = "cosik";
        		digest = MessageDigest.getInstance("SHA");
        		digest.update(passphrase.getBytes());
        		key = new SecretKeySpec(digest.digest(), 0, 16, "AES");
        	} catch (NoSuchAlgorithmException e1) {
        		System.out.println(e1);
        	}
        }
        return key;
	}
	
	public byte[] cipher(String text){
        
        try {
        	aes = Cipher.getInstance("AES/ECB/PKCS5Padding");
			aes.init(Cipher.ENCRYPT_MODE, Ciphering.Key());
			byte[] ciphertext = aes.doFinal(text.getBytes());
			return ciphertext;
		} catch (NoSuchPaddingException | NoSuchAlgorithmException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
			System.out.println(e);
		}
        return null;
	}
	public String decypher(byte[] ciphered) {
		String cleartext = null;
		try {
			aes = Cipher.getInstance("AES/ECB/PKCS5Padding");
			aes.init(Cipher.DECRYPT_MODE, Ciphering.Key());
			cleartext = new String(aes.doFinal(ciphered));
		} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
			System.out.println(e);
		}
		return cleartext;
	}
}
